package com.riguz.forks.framework.util;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riguz.gags.base.Strings;

public final class ServletUtil {

    public static boolean isAJAX(HttpServletRequest request) {
        return request.getHeader("X-Requested-With") != null;
    }

    public static String getRequestPath(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        String pathInfo = Strings.nullToEmpty(request.getPathInfo());
        return servletPath + pathInfo;
    }

    public static String formatUrl(String url) {
        if (Strings.isNullOrEmpty(url)) return "";
        return url.replaceAll("\\\\", "/").replaceAll("//+", "/");
    }

    public static void forward(HttpServletRequest request, HttpServletResponse response, String path) {
        try {
            RequestDispatcher dispatcher = request.getRequestDispatcher(path);
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void redirect(HttpServletRequest request, HttpServletResponse response, String path) {
        try {
            response.sendRedirect(request.getContextPath() + path);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, String[]> getRequestParamMap(HttpServletRequest request) {
        Map<String, String[]> paramMap = new LinkedHashMap<>();
        paramMap.putAll(request.getParameterMap());
        return paramMap;
    }

}
